<template>
	<el-dialog :title="form.id ? $t('common.editBtn') : $t('common.addBtn')" v-model="visible" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="24" class="mb20">
					<el-form-item prop="pid" :label="$t('ProdCategory.pid')">
						<SelectTree v-model="form.pid"></SelectTree>

						<!-- <el-tree-select
                v-model="form.pid"
                :data="parentData"
                :render-after-expand="false"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                class="w100"
                clearable
                check-strictly
                :placeholder="$t('ProdCategory.inputPidTip')"
            >
            </el-tree-select> -->
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item prop="name" :label="$t('ProdCategory.name')">
						<el-input v-model="form.name" :placeholder="$t('ProdCategory.inputNameTip')" clearable show-word-limit :maxlength="50" />
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item :label="$t('ProdCategory.icon')" prop="icon">
						<IconSelector :placeholder="$t('ProdCategory.inputIconTip')" v-model="form.icon" />
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item :label="$t('ProdCategory.pic')" prop="icon">
						<upload-img v-model:image-url="form.pic" />
					</el-form-item>
				</el-col>

        <el-col :span="24" class="mb20">
          <el-form-item :label="$t('ProdCategory.selectedPic')" prop="icon">
            <upload-img v-model:image-url="form.selectedPic" />
          </el-form-item>
        </el-col>

				<el-col :span="24" class="mb20">
					<el-form-item prop="isShow" :label="$t('ProdCategory.isShow')">
						<el-switch v-model="form.isShow" />
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item prop="sort" :label="$t('ProdCategory.sort')">
						<el-input-number v-model="form.sort" controls-position="right" />
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item :label="$t('ProdCategory.path')" prop="path" :disabled="true" v-if="form.id">
						<el-input v-model="form.path" :placeholder="$t('ProdCategory.inputPathTip')" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="ProdCategoryDialog">
import { useMessage } from '/@/hooks/message';
import { addObj, getObj, putObj } from '/@/api/bizs/ProdCategory';
// 定义i18n
import { useI18n } from 'vue-i18n';
// 定义字典
import { useDict } from '/@/hooks/dict';
// 上级菜单数据
// const parentData = ref([])
// 定义校验规则
import UploadImg from '/@/components/Upload/Image.vue';

const emit = defineEmits(['refresh']);

const { t } = useI18n();

const { yes_no_type } = useDict('yes_no_type');

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/IconSelector/index.vue'));
const SelectTree = defineAsyncComponent(() => import('/@/components/biz/selectTreeCom.vue'));
// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const dataFormRef = ref();

// 提交表单数据
const form = reactive({
	id: '',
	pid: '',
	name: '',
	level: '',
	isShow: 1,
	sort: 0,
	icon: '',
	path: '',
	pic: '',
  selectedPic:""
});

// 上级菜单数据
// const parentData = ref([])
const dataRules = ref({
	pid: [{ required: false, message: t('ProdCategory.inputPidTip'), trigger: 'blur' }],
	name: [{ required: true, message: t('ProdCategory.inputNameTip'), trigger: 'blur' }],
	level: [{ required: false, message: t('ProdCategory.inputLevelTip'), trigger: 'blur' }],
	isShow: [{ required: false, message: t('ProdCategory.inputIsShowTip'), trigger: 'blur' }],
	sort: [{ required: false, message: t('ProdCategory.inputSortTip'), trigger: 'blur' }],
});

// 打开弹窗
const openDialog = (type: string, row?: any) => {
	visible.value = true;
	form.id = '';

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
		form.pid = row?.id || '-1';
	});

	if (row?.id && type === 'edit') {
		form.id = row.id;
		initFormData(row.id);
	}
	// 渲染上级菜单列表树
	// getAllMenuData();
};

// 初始化表单数据
const initFormData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj(id)
		.then((res: any) => {
			Object.assign(form, res.data);
		})
		.finally(() => {
			loading.value = false;
		});
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? t('common.editSuccessText') : t('common.addSuccessText'));
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 从后端获取菜单信息（含层级）
// const getAllMenuData = () => {
//   parentData.value = [];
//   getTree({
//     type: '0',
//   }).then((res) => {
//     let menu = {
//       id: '-1',
//       name: '根菜单',
//       children: [],
//     };
//     menu.children = res.data;
//     parentData.value.push(menu);
//   });
// };

// 暴露变量
defineExpose({
	openDialog,
});
</script>
